package com.example.studentalarm.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.studentalarm.constant.DbConstant;
import com.example.studentalarm.utils.LogUtil;


/**
 * Created by Administrator
 * <p/>
 * 创建数据库
 */
public class DbOpenHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "student_base.db";
    private static final int DATABASE_VERSION = 1;
    private static DbOpenHelper instance;


    /**
     * 课程表
     **/
    private static final String CREATE_TIMETABLE_TABLE = "CREATE TABLE " + DbConstant.TIMETABLE.TABLE_NAME + " ("
            + DbConstant.TIMETABLE.COLUMN_NAME_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + DbConstant.TIMETABLE.COLUMN_NAME_NAME + " TEXT, " + DbConstant.TIMETABLE.COLUMN_NAME_ADDRESS + " TEXT, "
            + DbConstant.TIMETABLE.COLUMN_NAME_NOTE + " TEXT, " + DbConstant.TIMETABLE.COLUMN_NAME_ALARM_STATE + " INTEGER, "
            + DbConstant.TIMETABLE.COLUMN_NAME_MINUTE + " INTEGER, "
            + DbConstant.TIMETABLE.COLUMN_NAME_TIME + " LONG, "
            + DbConstant.TIMETABLE.COLUMN_NAME_DATE + " TEXT);";

    public DbOpenHelper(Context context) {
        super(context, getUserDatabaseName(), null, DATABASE_VERSION);
    }

    public static DbOpenHelper getInstance(Context context) {
        if (instance == null) {
            synchronized (DbOpenHelper.class) {
                if (instance == null) {
                    instance = new DbOpenHelper(context.getApplicationContext());
                }
            }
        }
        return instance;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        LogUtil.e("创建表......");
        db.execSQL(CREATE_TIMETABLE_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        LogUtil.e("旧版本" + oldVersion + "新版本：" + newVersion);

    }

    private static String getUserDatabaseName() {
        return DATABASE_NAME;
    }


    /**
     * 删除数据库
     *
     * @return
     */
    public void deleteDb() {
        SQLiteDatabase db = getWritableDatabase();
        db.delete(DbConstant.TIMETABLE.TABLE_NAME, null, null);
        db.close();
        closeDB();
    }

    public void closeDB() {
        if (instance != null) {
            try {
                SQLiteDatabase db = instance.getWritableDatabase();
                db.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            instance = null;
        }
    }
}
